package com.example.navigation

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.navigation.api.TokenInterceptor
import com.example.navigation.api.login.LoginApi
import com.example.navigation.ui.theme.NavigationTheme
import com.example.navigation.viewModel.LoginViewModel
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class LoginActivity : ComponentActivity() {

    private val loginViewModel: LoginViewModel by viewModels<LoginViewModel>()

    @Inject
    lateinit var tokenInterceptor: TokenInterceptor

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        val sharedPref: SharedPreferences = this@LoginActivity.getSharedPreferences(Constants.store_key, Context.MODE_PRIVATE)


        val useStr = sharedPref.getString("user", "")

        Log.i(this.toString(), "onCreate: $useStr")

        if (useStr!!.isNotEmpty()) {
            // 已经登录过有用户信息
            val userInfo = Gson().fromJson(useStr, LoginApi.UserInfo::class.java)
            // 读取token给okhttp拦截器添加请求token
            tokenInterceptor.token = userInfo.token
            // 跳转到主页面不需要登录了
            startActivity(Intent(baseContext, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
            finish()
        }

        setContent {
            NavigationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        modifier = Modifier.padding(innerPadding),
                        loginViewModel,
                        loginActivity = this@LoginActivity,
                        sharedPref
                    )
                }
            }
        }
    }
}

@Composable
fun Greeting(
    modifier: Modifier = Modifier,
    loginViewModel: LoginViewModel,
    loginActivity: LoginActivity,
    sharedPref: SharedPreferences
) {
    var username by remember {
        mutableStateOf("admin")
    }
    var password by remember {
        mutableStateOf("123456")
    }

    LaunchedEffect(key1 = Unit) {
        loginViewModel.loginRes.collect {
            if (it.code == 1) {
                Toast.makeText(loginActivity, "登录成功", Toast.LENGTH_SHORT).show()
                // 本地保存token
                with(sharedPref.edit()) {
                    putString("user", Gson().toJson(it.data))
                    commit()
                }
                loginActivity.startActivity(
                    Intent(loginActivity, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )
                loginActivity.finish()
            }
        }
    }

    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text("走航系统", fontSize = 20.sp)

        Spacer(modifier = Modifier.height(30.dp))


        TextField(value = username, onValueChange = {
            username = it
        }, label = {
            Text(text = "用户名")
        })

        TextField(value = password, onValueChange = {
            password = it
        }, label = {
            Text(text = "密码:")
        })

        Button(onClick = {
            loginViewModel.login(LoginApi.LoginParams(username, password, true))
        }) {
            Text(text = "登录")
        }
    }
}
